//
//  Status.swift
//  Status
//
//  Created by 花轮 on 15/5/18.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit
import SDWebImage

private let WB_Home_URL = "https://api.weibo.com/2/statuses/friends_timeline.json"

class Status: NSObject {
    // 创建时间
    var created_at: String?
    // 用户id
    var id: Int = 0
    // 正文
    var text: String?
    // 来源
    var source: String?
    // 图片url数组
    var pic_urls: [[String: String]]?{
        didSet{
            // 实例化图片url数组
            imageURLs = [NSURL]()
            largeURLs = [NSURL]()
            
            for arr in pic_urls!{
                if let urlstr = arr["thumbnail_pic"]
                {
                    let largeStr = (urlstr as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    
                    imageURLs?.append(NSURL(string: urlstr)!)
                    largeURLs?.append(NSURL(string: largeStr)!)
                }
            }
//            println(largeURLs)
        }
    }
    
    // 缩略图的URL数组
    private var imageURLs: [NSURL]?
    
    // 大图的URL数组
    private var largeURLs: [NSURL]?
    
    var pictureURLs: [NSURL]?{
        return retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    }
    
    var largePicURLs: [NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.largeURLs : largeURLs
    }
    
    var user: User?
    
    var retweeted_status: Status?
    
    static let properties = ["created_at", "id", "text", "source", "pic_urls", "retweeted_status"]
    
    // 加载微博数据
    class func loadStatus(completion:(statuses: [Status]?) -> ()) {
        let params = ["access_token": sharedUserAccount!.access_token];
        
        NetworkTools.requestJSON(.GET, URLStr: WB_Home_URL, parameters: params) { (JSON) -> () in
            if JSON != nil
            {
                if let array = (JSON as! NSDictionary)["statuses"] as? [[String: AnyObject]]
                {
                    
                    let result = self.statuses(array)
                    
                    self.cacheStatusImages(result, completion: completion)
                    
                    return
                }
            }
            completion(statuses: nil)
        }
    }
    
    
    private class func cacheStatusImages(statuses: [Status]?, completion:(statuses: [Status]?)->())
        {
        if statuses?.count == 0
        {
            return
        }
        
        let group = dispatch_group_create()
        
        for s in statuses as [Status]!{
            if s.pictureURLs == nil
            {
                continue
            }
            
            for url in s.pictureURLs!{
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: nil, progress: nil, completed: { (_, _, _, _, _)  in
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            println("图片缓存完成\(NSHomeDirectory())")
            
            completion(statuses: statuses)
        }
    }
    
    private class func statuses(array:[[String: AnyObject]]) ->[Status]?
    {
        if array.count == 0
        {
            return nil
        }
        var arrM = [Status]()
        
        for dict in array{
            arrM.append(Status(dict: dict))
        }
        
        return arrM
    }
    
    init(dict: [String: AnyObject])
    {
        super.init()
        
        for k in Status.properties{
            if dict[k] != nil
            {
//                setValuesForKeysWithDictionary(dict)
                setValue(dict[k], forKeyPath: k)
            }
        }
        
        if dict["user"] != nil{
            user = User(dict: dict["user"] as! [String: AnyObject])
        }
        
        if dict["retweeted_status"] != nil{
            retweeted_status = Status(dict: dict["retweeted_status"] as! [String: AnyObject])
        }
    }
}
